<script>
	import TencentCloudChat from '@tencentcloud/chat';
	import {TUIChatKit, genTestUserSig} from "./TUIKit";
	import {vueVersion} from "./TUIKit/adapter-vue";
	import {TUILogin} from "@tencentcloud/tui-core";

	import constant from '@/common/constant.js'
	export default {
		globalData: {
			webUrl: '',
			webTitle: '',
			chatUserId: '',
			chatTxCode: '',
			callerId: '',
			timeCall: {},
			versionName: '',
			openTicketMin: false,
			ticketStartTime: 0,
			ticketTotalTime: 180,
		},
		onLaunch: function() {
			this.initIM();
			this.checkUpdate();
			this.isLogin();
			uni.$online = constant.online;
		},

		methods: {
			isLogin() {
				const login = uni.getStorageSync("login");
				if (!login) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}
			},
			initIM() {
				const config = {
					SDKAppID: constant.imApppId, // Your SDKAppID
					secretKey: constant.imSecretKey,
				}
				uni.$chat_SDKAppID = config.SDKAppID;
				uni.$chat_secretKey = config.secretKey;

				uni.$TUIKit = TencentCloudChat.create({
					SDKAppID: config.SDKAppID
				});
				TUIChatKit.init();
				// #ifdef APP-PLUS || H5
				// const TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
				// uni.$TUICallKit = TUICallKit;
				// #endif
				this.loginIM();
			},
			loginIM() {
				const txCode = uni.getStorageSync("userTxCode");
				const token = uni.getStorageSync("token");
				if (txCode && token) {
					const config = {
						userID: '' + txCode,
						SDKAppID: uni.$chat_SDKAppID,
						secretKey: uni.$chat_secretKey,
					}
					uni.$chat_userSig = genTestUserSig(config).userSig;

					const options = {
						SDKAppID: uni.$chat_SDKAppID,
						userID: '' + txCode,
						userSig: uni.$chat_userSig,
						useUploadPlugin: true,
						framework: `vue${vueVersion}`
					};
					//IM登录
					TUILogin.login(options).then(res => {
						console.log("IM登录成功：" + JSON.stringify(res));
						this.initUnReadMessage();
						uni.$emit("requestHome");
					}).catch(error => {
						console.log('IM登录失败:' + JSON.stringify(error));
					});
					//音视频登录
					// #ifdef APP-PLUS || H5
					// uni.$TUICallKit.login(options, (res) => {
					// 	if (res.code === 0) {
					// 		console.log("音视频登录成功：" + JSON.stringify(res));
					// 		this.initListenerCall();
					// 	} else {
					// 		console.log(`音视频登录失败, error message = ${res.msg}`);
					// 	}
					// });
					// #endif
				}
			},
			initUnReadMessage() {
				//异地登录
				uni.$TUIKit.on(TencentCloudChat.EVENT.KICKED_OUT, function(event) {
					console.log("异地登录");
					uni.showToast({
						title: 'IM被踢出，请重新登录',
						icon: 'none'
					});
					uni.reLaunch({
						url: '/pages/login/login'
					});
					uni.removeStorageSync('login');
				});
				uni.$TUIKit.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, event => {
					// console.log("未读消息数量监听："+JSON.stringify(event));
					this.setUnReadMessageCount(event.data);
				});
				setTimeout(() => {
					uni.$TUIKit.getConversationList().then(res => {
						// console.warn('获取会话列表成功:', JSON.stringify(res.data.conversationList));
						const unReadMessageCount = uni.$TUIKit.getTotalUnreadMessageCount();
						// console.log("unReadMessageCount："+unReadMessageCount);
						this.setUnReadMessageCount(unReadMessageCount);
					}).catch(error => {
						// console.warn('获取会话列表失败:', error);
					});
				}, 1000);

			},
			setUnReadMessageCount(count) {
				console.log("count：" + count);
				if (count > 0) {
					uni.setTabBarBadge({
						index: constant.messageIndex,
						text: '' + count
					})
				} else {
					uni.removeTabBarBadge({
						index: constant.messageIndex
					})
				}
			},
			initListenerCall() {
				// const TUICallKitEvent = uni.requireNativePlugin('globalEvent');
				// TUICallKitEvent.addEventListener('onError', (res) => {
				// 	console.log('音视频-错误', JSON.stringify(res));
				// });
				// TUICallKitEvent.addEventListener('onCallReceived', (res) => {
				// 	this.globalData.callerId = res.callerId;
				// 	console.log('音视频-接听', JSON.stringify(res));
				// });
				// TUICallKitEvent.addEventListener('onCallCancelled', (res) => {
				// 	console.log('音视频-取消', res);
				// });
				// TUICallKitEvent.addEventListener('onCallBegin', (res) => {
				// 	console.log('音视频-开始', JSON.stringify(res));
				// 	this.startCallTime(res);
				// });
				// TUICallKitEvent.addEventListener('onCallEnd', (res) => {
				// 	console.log('音视频-结束', JSON.stringify(res));
				// 	clearInterval(this.timeCall);
				// });
			},

			startCallTime(res) {
				this.requestCall(res);
				console.log("startCallTime");
				this.timeCall = setInterval(() => {
					this.requestCall(res);
				}, 10 * 1000);
			},

			//男号：音视频扣费
			async requestCall(res) {
				// {"callMediaType":1,"roomID":441833970,"callRole":1}--主动拨打
				//{"callMediaType":1,"roomID":319954761,"callRole":2}---被动接听：如果是男号被动接听，如何获取扣费用户id?(onCallReceived的callerId字段)
				const sex = uni.getStorageSync('userSex');
				if (1 == sex) {
					let type = res.callMediaType == 1 ? '2' : '3';
					let txCode = res.callRole == 1 ? this.globalData.chatTxCode : this.globalData.callerId;
					let params = {
						type: type, //扣费类型：2.音频通话；3.视频通话；4.语音速配；5.视频速配
						txCode: txCode, //callerId为女号腾讯code
					};
					let header = {
						token: uni.getStorageSync('token')
					}
					header['content-type'] = 'application/x-www-form-urlencoded';
					uni.request({
						url: constant.baseUrl + "/app/user/feeDeduction",
						header: header,
						data: params,
						success: (res) => {
							console.log(JSON.stringify(res));
							if (0 !== res.data.code) {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
								//钻石不够主动挂断
								// const TUICallEngine = uni.requireNativePlugin('TencentCloud-TUICallKit-TUICallEngine');
								// TUICallEngine.hangup();
								//后续弹出充值对话框
							}
						}
					})
				}
			},

			clearUserCache() {
				uni.removeStorageSync('token');
				uni.removeStorageSync('userId');
				uni.removeStorageSync('userName');
				uni.removeStorageSync('userPic');
				uni.removeStorageSync('userSex');
				uni.removeStorageSync('userTxCode');
			},

			//检查更新
			checkUpdate() {
				// #ifdef APP-PLUS
				plus.runtime.getProperty(plus.runtime.appid, (info) => {
					this.versionName = info.version;
				});
				let urlstr = "https://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/uniapp_android/poposeConfig-hw.json?t=" + new Date().getTime();
				// let urlstr = "https://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/uniapp_android/testConfig.json?t=" + new Date().getTime();
				uni.request({
					url: urlstr,
					success: (res) => {
						// clearInterval(this.timers);
						// console.log("配置文件: " + JSON.stringify(res));
						uni.setStorageSync('vipManage', res.data.vipManage);
						uni.setStorageSync('ticketPrice', res.data.ticketPrice);
						if(res.data.ticketTime){
							this.globalData.ticketTotalTime = res.data.ticketTime
						}

						if (res.data.open == "1" && res.data.vss != this.versionName) {
							this.install(res.data.wgtUrl);
						}
					}
				})
				// #endif
			},

			//wgt下载安装
			install(wgtUrl) {
				// #ifdef APP-PLUS
				plus.downloader.createDownload(wgtUrl, {
					filename: "_doc/update/"
				}, (d, status) => {
					if (status == 200) {
						plus.runtime.install(d.filename, {
							force: true
						}, function() {
							plus.nativeUI.closeWaiting();
							plus.runtime.restart();
						}, function(e) {
							plus.nativeUI.closeWaiting();
						});
					} else {
						plus.nativeUI.closeWaiting();
					}
				}).start();
				// #endif
			},
			toTicket(){
				if(0 == this.globalData.ticketStartTime){
					let timeId = setInterval(()=>{
						console.log('ticket--start', this.globalData.ticketStartTime);
						this.globalData.ticketStartTime++
						if(this.globalData.ticketStartTime == this.globalData.ticketTotalTime){
							clearInterval(timeId)
							uni.setStorageSync("ticketOver"+uni.getStorageSync('userId'), true)
							this.globalData.ticketStartTime = 0
							this.globalData.openTicketMin = true
							uni.reLaunch({
								url: '/pages/tab/home/home',
							});
						}
					}, 1000)
				}
			}

		}
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import '@/uni_modules/uni-scss/index.scss';
	/* #ifndef APP-NVUE */
	@import '@/static/customicons.css';
	// 设置整个项目的背景色
	@import '@/common/uni.css';
	//uview的基础样式
	@import "uview-ui/index.scss";

	page {
		background-color: #f5f5f5;
	}

	/* #endif */
	.example-info {
		font-size: 14px;
		color: #333;
		padding: 10px;
	}
</style>